package com.easytouch.core.encryption;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 * Created by gulin on 2016/9/13.
 */
public class MD5 {
    /**
     * MD5加密
     *
     * @param msg 要加密的串
     * @return
     */
    public static String md5Encode(String msg) {
        String result;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = digest.digest(msg.getBytes("UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = md5Bytes[i] & 0xff;
                if (val < 16) {
                    builder.append("0");
                }
                builder.append(Integer.toHexString(val));
            }
            result = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            result = "";
        } catch (UnsupportedEncodingException e) {
            result = "";
        }
        return result;
    }
}
